import {Request, Response, NextFunction, Router} from "express";
import {Repository} from "sequelize-typescript";
import request from "request";
import {validationResult, body} from 'express-validator'
import md5 from 'md5'

import config from '../config'
import {User, Admin} from "../models";
import {checkToken, generateToken, analysisToken} from '../middlewares/jwt'

interface BodyRequestBody extends Request {
    body: {
        [key: string]: string | undefined
    }
}

const userRouterFactory = (
    userRepository: Repository<User>,
    adminRepository: Repository<Admin>,
    ) => Router()
        .post('/login/wx', [
                body('code').isLength({min: 1})
            ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                const error = validationResult(req)
                if (!error.isEmpty()) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: error.array()
                    })
                }
                const code = req.body.code
                let userInfo: any = undefined
                if (req.body.userInfo) {
                    userInfo = JSON.parse(req.body.userInfo)
                }
                // console.log(userInfo);
                try {
                    const appid = config.wx.appid;
                    const secret = config.wx.secret;
                    const authorizationCode = config.wx.authorizationCode;

                    // 向微信服务器发送信息获取到 openid 和 session_key
                    request.get({
                        url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=${authorizationCode}`
                    }, async (err: any, response: any, body: string) => {
                        if (err) {
                            return res.json({
                                errCode: 10001,
                                msg: '操作失败'
                            })
                        }
                        const data = JSON.parse(body);
                        // console.log(data);
                        const {openid} = data
                        const list = await userRepository.findOne({
                                where: {
                                    user_appId: openid
                                }
                            }
                        )
                        const token = generateToken(openid)
                        if (list) {
                            return res.json({
                                code: 1,
                                msg: '获取用户信息成功',
                                data: list,
                                token
                            })
                        } else {
                            const regist = await userRepository.create({
                                user_appId: openid,
                                user_name: userInfo.nickName,
                                user_picture: userInfo.avatarUrl,
                                user_sex: userInfo.gender
                            })
                            if (regist) {
                                return res.json({
                                    code: 1,
                                    msg: '用户注册成功',
                                    data: regist,
                                    token
                                })
                            }
                        }

                        // return res.json({
                        //     code: 1,
                        //     data: data
                        // })
                    })
                    // return res.json({
                    //     errCode: 10001,
                    //     msg: '操作失败'
                    // })
                } catch (e) {
                    res.json({
                        errCode: 10001,
                        msg: '操作失败'
                    })
                    next()
                }
            }
        )

        .post('/login/h5', [
                body('user_phone').isMobilePhone('zh-CN'),
                body('user_password').isLength({min: 3})
            ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                const error = validationResult(req)
                if (!error.isEmpty()) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: error.array()
                    })
                }
                const user_phone = req.body.user_phone;
                const user_password = req.body.user_password;
                if (!user_phone || !user_password) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: '请输入账号密码'
                    })
                }
                try {
                    const data = await userRepository.findOne({
                            where: {
                                user_phone: user_phone
                            }
                        }
                    )
                    if (data) {
                        let token = generateToken(user_phone)
                        const r = await userRepository.findOne({
                                where: {
                                    user_phone: user_phone,
                                    user_password: md5(user_password)
                                }
                            }
                        )
                        if (r) {
                            return res.json({
                                code: 1,
                                msg: '获取用户信息成功',
                                data: r,
                                token
                            })
                        } else {
                            return res.json({
                                code: 0,
                                msg: '账号密码不正确'
                            })
                        }

                    } else {
                        return res.json({
                            code: 0,
                            msg: '请先注册账号'
                        })
                    }

                    // return res.json({
                    //     code: 1,
                    //     data: data
                    // })
                    // return res.json({
                    //     errCode: 10001,
                    //     msg: '操作失败'
                    // })
                } catch (e) {
                    res.json({
                        errCode: 10001,
                        msg: '操作失败'
                    })
                    next()
                }
            }
        )
        .post('/register/h5', [
                body('user_name').isLength({min: 1}),
                body('user_phone').isMobilePhone('zh-CN'),
                body('user_password').isLength({min: 3}),
                body('user_picture').isLength({min: 1}),
                body('user_sex').isLength({min: 1}),
            ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                const error = validationResult(req)
                if (!error.isEmpty()) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: error.array()
                    })
                }
                let user_name = req.body.user_name;
                let user_phone = req.body.user_phone;
                let user_password = req.body.user_password;
                let user_picture = req.body.user_picture;
                let user_sex = req.body.user_sex;
                if (user_password) {
                    user_password = md5(user_password)
                }
                if (!user_phone) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: '请输入账号'
                    })
                }
                try {
                    const data = await userRepository.findOne({
                            where: {
                                user_phone: user_phone
                            }
                        }
                    )
                    if (data) {
                        return res.json({
                            code: 0,
                            msg: '该用户已存在'
                        })
                    } else {
                        const regist = await userRepository.create({
                            user_name: user_name,
                            user_phone: user_phone,
                            user_password: user_password,
                            user_picture: user_picture,
                            user_sex: user_sex
                        })
                        if (regist) {
                            return res.json({
                                code: 1,
                                msg: '用户注册成功',
                                data: regist
                            })
                        } else {
                            return res.json({
                                code: 0,
                                msg: '注册失败'
                            })
                        }

                    }
                } catch (e) {
                    console.log(e);
                    res.json({
                        errCode: 10001,
                        msg: '操作失败'
                    })
                    next()
                }
            }
        )

        .post('/admin/login', [
                body('account').isLength({min: 1}),
                body('password').isLength({min: 1}),
            ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                const error = validationResult(req)
                if (!error.isEmpty()) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: error.array()
                    })
                }
                let account = req.body.account
                let password = req.body.password

                if (!account || !password) {
                    return res.json({
                        code: 0,
                        msg: '请输入账号密码'
                    })
                }

                let token = generateToken(account)
                const r = await adminRepository.findOne({
                        where: {
                            account: account,
                            password: password
                        }
                    }
                )
                if (r) {
                    return res.json({
                        code: 1,
                        msg: '登录成功',
                        data: r,
                        token
                    })
                }
                return res.json({
                    code: 0,
                    msg: '登录失败',
                })
            }
        )
        .get('/admin/detail', async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                let qCode: any = await analysisToken(req, res, next)
                if (qCode.errCode) {
                    return res.send(qCode)
                }
                const r = await adminRepository.findOne({
                        where: {
                            account: qCode.userId
                        }
                    }
                )
                if (r) {
                    return res.json({
                        code: 1,
                        msg: '获取详情成功',
                        data: r
                    })
                }
                // let account = req.body.account
                // let password = req.body.password

                // if (!account || !password) {
                //     return res.json({
                //         code: 0,
                //         msg: '请输入账号密码'
                //     })
                // }

                // let token = generateToken(account)
                // const r = await adminRepository.findOne({
                //         where: {
                //             account: account
                //         }
                //     }
                // )
                // if (r) {
                //     return res.json({
                //         code: 1,
                //         msg: '登录成功',
                //         data: r,
                //         token
                //     })
                // }
                // return res.json({
                //     code: 0,
                //     msg: '登录失败',
                // })
            }
        )
        .get('/all', checkToken, async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                try {
                    const list = await userRepository.findAll()
                    if (list) {
                        return res.json({
                            code: 1,
                            data: list
                        })
                    }
                    return res.json({
                        errCode: 10001,
                        msg: '数据获取失败'
                    })
                } catch (e) {
                    console.log(e);
                    next()
                }

            }
        )
        .post('/delUser', checkToken, [
                body('id').isLength({min: 1}),
            ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                const error = validationResult(req)
                if (!error.isEmpty()) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: error.array()
                    })
                }
                try {
                    const id = req.body.id
                    if (!id) {
                        return res.json({
                            errCode: 10001,
                            msg: '操作失败'
                        });
                    }
                    const list = await userRepository.destroy({
                        where: {
                            id: id
                        }
                    })
                    if (list) {
                        console.log('--- 删除成功 ---');
                        return res.json({
                            code: 1,
                            msg: '删除成功'
                        })
                    }
                    return res.json({
                        errCode: 10001,
                        msg: '操作失败'
                    })
                } catch (e) {
                    console.log(e);
                    next()
                }
            }
        )
        .post('/detail', checkToken, [
                body('id').isLength({min: 1}),
            ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                const error = validationResult(req)
                if (!error.isEmpty()) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: error.array()
                    })
                }
                try {
                    const id = req.body.id
                    if (!id) {
                        return res.json({
                            errCode: 10001,
                            msg: '操作失败'
                        });
                    }
                    const list = await userRepository.findOne({
                        where: {
                            id: id
                        }
                    })
                    if (list) {
                        return res.json({
                            code: 1,
                            data: list,
                            msg: '查询成功'
                        })
                    }
                    return res.json({
                        errCode: 10001,
                        msg: '操作失败'
                    })
                } catch (e) {
                    console.log(e);
                    next()
                }
            }
        )
        .post('/fixUser', checkToken, [
                body('id').isLength({min: 1}),
                body('edu_class').isLength({min: 1}),
                body('edu_account').isLength({min: 1}),
                body('edu_password').isLength({min: 1}),
            ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                const error = validationResult(req)
                if (!error.isEmpty()) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: error.array()
                    })
                }
                try {
                    const id = req.body.id
                    const {edu_class, edu_account, edu_password} = req.body
                    if (!id || !edu_class || !edu_account || !edu_password) {
                        return res.json({
                            errCode: 10001,
                            msg: '操作失败,请输入完整信息!'
                        });
                    }
                    const r = await userRepository.update({
                        edu_class,
                        edu_account,
                        edu_password
                    }, {
                        where: {
                            id: id
                        }
                    })
                    console.log(r);
                    const list = await userRepository.findOne({
                        where: {
                            id: id
                        }
                    })
                    if (list) {
                        console.log('--- 更新成功 ---');
                        return res.json({
                            code: 1,
                            data: list,
                            msg: '学生信息认证成功!'
                        })
                    }
                    return res.json({
                        errCode: 10001,
                        msg: '操作失败'
                    })
                } catch (e) {
                    console.log(e);
                    next()
                }
            }
        )

;
export default userRouterFactory
